#!/bin/bash
#
# 构建、运行工程镜像
UP_DOWN="$1"

DOCKER_IMAGE_IDS=
IMAGES_NAME="eureka config api" # 镜像名称
COMPOSE_FILE=docker-compose.yml

SCRIPT_PATH=`pwd`
ENGINEERING_PATHS="eureka-server config-server api" # 项目名称
LOG_PATH=logs/

function up() {
    cd $SCRIPT_PATH
    cd ..
    CODE_PATH=`pwd`
    echo "CODE_PATH is:" $CODE_PATH
    echo "============STEP 1. update code============="
#    cd $CODE_PATH
#    git pull http://a:1q2w3e4r@git.hnluchuan.com/bodyclock/crm.git

    echo "============STEP 2. stop and rm docker container=============="
    dockerComposeDown

    echo "============STEP 3. rmi docker images=============="
    dockerRmiImages

    echo "============STEP 4. build docker images=============="
    dockerBuildImages

    echo "============STEP 5. up docker-compose=============="
    dockerComposeUp

    echo "============End Up Function=============="
}

function dockerComposeUp() {
    cd $SCRIPT_PATH
    docker-compose -f $COMPOSE_FILE up -d 2>&1
}

function dockerComposeDown() {
    cd $SCRIPT_PATH
    docker-compose -f $COMPOSE_FILE down
}

function dockerRmiImages() {
    for NAMES in $IMAGES_NAME; do
        DOCKER_IMAGE_ID=$(docker images | grep $NAMES | awk '{print $3}')
        if [ "$DOCKER_IMAGE_ID" = "" ]; then
          echo ""
        else
          DOCKER_IMAGE_IDS+=" "$DOCKER_IMAGE_ID
        fi
    done
    echo "==> IMAGES_NAME: $IMAGES_NAME"
    echo "==> DOCKER_IMAGE_IDS: $DOCKER_IMAGE_IDS"
    echo
    if [ -z "$DOCKER_IMAGE_IDS" -o "$DOCKER_IMAGE_IDS" = "" ]; then
        echo "---- No images available for deletion ----"
    else
        docker rmi -f $DOCKER_IMAGE_IDS
    fi
}

function dockerBuildImages() {
    cd $SCRIPT_PATH
    cd ..
    CODE_PATH=`pwd`
    for ENGINEERING_PATH in $ENGINEERING_PATHS; do
        echo "ENGINEERING_PATH =====> $CODE_PATH/$ENGINEERING_PATH"
        echo
        cd $CODE_PATH/$ENGINEERING_PATH
        mvn clean package docker:build
    done
}

function printHelp() {
	echo "up"
}

if [ "${UP_DOWN}" == "up" ]; then
    up

    echo
    echo "===> List out docker images"
    docker images
    echo
    echo "===> List out docker ps -a"
    docker ps -a
else
	printHelp
	exit 1
fi

